package com.ebanma.cloud.user.service.impl;

import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ebanma.cloud.constant.RedisConstant;
import com.ebanma.cloud.dto.AjaxResult;
import com.ebanma.cloud.dto.UserDTO;
import com.ebanma.cloud.exception.BusinessException;
import com.ebanma.cloud.user.dao.mapper.UserMapper;
import com.ebanma.cloud.user.dao.po.User;
import com.ebanma.cloud.user.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ebanma.cloud.utils.JwtUtil;
import com.ebanma.cloud.utils.RedisUtil;
import com.ebanma.cloud.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wangxin
 * @since 2023-02-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private JwtUtil jwtUtil;


    @Autowired
    private UserMapper userMapper;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public AjaxResult regist(UserDTO userDTO) {
        //判断验证码是否正确
        String code =redisUtil.get(RedisConstant.CAPTCHA_CODE + userDTO.getPhone());
        if (!userDTO.getCode().equals(code)  ) {
            return AjaxResult.fail(201,"验证码不正确",null);
        }
        //判断是否曾经注册过
        if (userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone, userDTO.getPhone())) != null) {
            return AjaxResult.fail(201,"手机号已经注册",null);
        }
        //核对无误，可以注册，生成账号
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        //EM账号前缀
        String userId="EM"+ RandomUtil.randomString(6);
        user.setUserId(userId);
        return save(user)?AjaxResult.success(200,"创建账号成功",user):AjaxResult.fail(401,"创建账号失败",null);
    }

    @Override
    public AjaxResult loginByPhone(UserDTO userDTO) {
        //根据手机查询user
        LambdaQueryWrapper<User> eq = new LambdaQueryWrapper<User>().eq(User::getPhone, userDTO.getPhone());
        User user=null;
             //登录验证码code正确，且该用户在db中存在
            if (!(redisUtil.get(RedisConstant.CAPTCHA_CODE+userDTO.getPhone())).equals(userDTO.getCode()) || ((user=userMapper.selectOne(eq))==null)){
            return AjaxResult.fail(401,"验证码不正确，请重试",null);
        }
        //登录成功，将user存入redis,返回token
        String uuid= RedisConstant.LOGIN_TOKEN+ UUID.fastUUID().toString(true);
        redisUtil.setEx(uuid, JSONUtil.toJsonStr(user),RedisConstant.LOGIN_TTL, TimeUnit.MINUTES);
        Map<String, String> payload = new HashMap<>(16);
        //封装user对应的uuid
        payload.put(RedisConstant.LOGIN_TOKEN, uuid);
        String jwtToken = jwtUtil.createJwtToken(payload, Calendar.HOUR, 8);

        HashMap<String, Object> res = new HashMap<>(16);
        res.put(RedisConstant.JWT_TOKEN,jwtToken);
        //返回给前端应该过滤掉敏感字段
        user.setPassword(null);
        res.put("user",user);
        //将验证码通过三方平台发给用户
        //TODO
        return AjaxResult.success(200, "登录成功", res);
    }
}
